﻿<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%option explicit%>
<!--#include file="../Conn.asp"-->
<!--#include file="../Plus/md5.asp"-->
<!--#include file="../KS_Cls/Kesion.MemberCls.asp"-->
<!--#include file="payfunction.asp"-->
<%
'******************************************************************
' Software name:KesionCMS X1.5
' Email: service@kesion.com . 营销QQ:4000080263  Tel:400-008-0263
' Web: http://www.kesion.com http://www.kesion.cn
' Copyright (C) Kesion Network All Rights Reserved.
'******************************************************************
Response.Buffer = true 
Response.Expires = 0 
Response.CacheControl = "no-cache"

input_charset="utf-8"  '不可少,否则签名会出错 md5加密要用到

Dim KSUser:Set KSUser=New UserCls
Dim KS:Set KS=New PublicCls
Dim PaymentPlat:PaymentPlat=KS.ChkClng(Request("PaymentPlat"))
If PayMentPlat=0 And Request("c_memo1")<>"" Then PayMentPlat=KS.ChkClng(Split(Request("c_memo1"),"|")(0))  '判断是不是云网支付的
IF PaymentPlat=0 Then Response.Write("error!"):Response.End()

Dim RSP:Set RSP=Server.CreateObject("ADODB.RECORDSET")
RSP.Open "Select * From KS_PaymentPlat where id=" & PaymentPlat,conn,1,1
If RSP.Eof Then
		 RSP.Close:Set RSP=Nothing
		 Response.Write "Error!"
		 Response.End()
End If
Dim AccountID:AccountID=RSP("AccountID")
Dim MD5Key:MD5Key=RSP("MD5Key")
Dim PayOnlineRate:PayOnlineRate=KS.ChkClng(RSP("Rate")) 
Dim RateByUser:RateByUser=KS.ChkClng(RSP("RateByUser")) 
RSP.Close:Set RSP=Nothing

Select Case PaymentPlat
		 Case 1 '网银在线
		  Call ChinaBank()
		 Case 2 '中国在线支付网
		  Call ipayBack()
		 Case 3 '上海环迅
		  Call IpsBack()
		 Case 4 '易宝支付
		  Call YeepayBack()
		 Case 5 '易付通
		  Call xpayBack()
		 Case 6 '云网支付
		  Call cncardBack() 
		 Case 7 '支付宝
		  Call alipayBack()
		 Case 8 '快钱支付
		  Call billback()
		 Case 9,15  '支付宝担保交易及支付宝标准双接口
		  Call alipayBack9()
		 Case 10 '财付通
		  Call tenpayback()
		 Case 11 '财付通中介交易
		  Call tenpayZJ()
		 case 12,13  'paypal 国际版
		  Call PayPal()
End Select 

'paypal 国际版
Sub PayPal()
    dim str1,str2,str,paypalurl,objHttp,ResponseTxt,sParts,iParts,sKey,sValue,sResults,Msg
	
    str1=Trim(KS.S("tx"))
	str2="&at=" &MD5Key                             '这里是Paypal身份标
	
	str = "?tx="&str1& "&cmd=_notify-synch"&str2
	'paypalurl="https://www.sandbox.paypal.com/cgi-bin/webscr"   '测试接口专用，正式使用要使用以下接口
	paypalurl="https://www.paypal.com/cgi-bin/webscr"            '正式环境使用此接口
	paypalurl=paypalurl&str
	
	Set objHttp=Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
	objHttp.setOption 2, 13056 
	objHttp.open "POST",paypalurl,False,"","" 
	objHttp.send()
	
	ResponseTxt = objHttp.ResponseText           '示例下面有写
	Set objHttp=Nothing
	'-------------------------------------------------核对取得值
	ResponseTxt=UrlDecodes(ResponseTxt)                '将返回值解码并赋给 responsetxt 
	
	'ks.echo ResponseTxt
	
	If Mid(ResponseTxt,1,7) = "SUCCESS" Then          '取得返回值的状态, sucess表示支付成功 ! Fail 表示支付失败 ! 返回值只有这两种情况 !
	ResponseTxt = Mid(ResponseTxt,9)                  '取得除了前9个字符的返回值,并返回给responsetxt
	sParts = Split(ResponseTxt, vbLf)                 '将返回值以vbLf(在vb里面这是回车<换行>的意思)分开,并赋给一个数组sParts
	iParts = UBound(sParts) - 1                      '对这个数组分离取值, 后面的应该都可以看得懂的吧!
	ReDim sResults(iParts, 1)
	dim v_oid,usdmoney,v_amount,remark2,v_pmode,i,aParts
	For i = 0 To iParts
	aParts = Split(sParts(i), "=")
	sKey = aParts(0)
	sValue = aParts(1)
	sResults(i, 0) = sKey
	sResults(i, 1) = sValue
	
	Select Case sKey
	Case "item_number"
	v_oid = Replace(Replace(KS.DelSQL(sValue),"'",""),"%","")
	Case "mc_gross"
	usdmoney = sValue
	v_amount=round(usdmoney*KS.Setting(81),2)
	Case "txn_id"
	 dim liushuihao:liushuihao = Trim(sValue)
	Case "payer_email"
	 dim payeremail: payeremail=Trim(sValue)
	End Select
	Next
	remark2="支付订单：" & v_oid &"费用!" 
	v_pmode="PayPal"
	Call UpdateOrder(v_amount,remark2,v_oid,v_pmode)
	Msg="恭喜，支付成功！"
	Else
	Msg="对不起支付失败，请联系本站管理员！"
	End If
	Call ShowResult(Msg)

End Sub

function urldecodes(encodestr)   '这个函数是对paypal返回值的urldecode解码的
	dim newstr:newstr="" 
	dim havechar:havechar=false 
	dim lastchar:lastchar="" 
	dim i,char_c,next_1_c,next_1_num
	for i=1 to len(encodestr) 
	char_c=mid(encodestr,i,1) 
	if char_c="+" then 
	newstr=newstr & " " 
	elseif char_c="%" then 
	next_1_c=mid(encodestr,i+1,2) 
	next_1_num=cint("&H" & next_1_c) 
	if havechar then 
	havechar=false 
	newstr=newstr & chr(cint("&H" & lastchar & next_1_c)) 
	else 
	if abs(next_1_num)<=127 then 
	newstr=newstr & chr(next_1_num) 
	else 
	havechar=true 
	lastchar=next_1_c 
	end if 
	end if 
	i=i+2 
	else 
	newstr=newstr & char_c 
	end if 
	next 
	urldecodes=newstr 
end Function

'网银在线返回
Sub ChinaBank() 
 Dim v_oid,v_pmode,v_pstatus,v_pstring,v_string,v_amount,v_moneytype,remark2,v_md5str,text,md5text,zhuangtai
' 取得返回参数值
	v_oid=KS.S("v_oid")                               ' 商户发送的v_oid定单编号
	v_pmode=request("v_pmode")                           ' 支付方式（字符串） 
	v_pstatus=request("v_pstatus")                       ' 支付状态 20（支付成功）;30（支付失败）
	v_pstring=request("v_pstring")                       ' 支付结果信息 支付完成（当v_pstatus=20时）；失败原因（当v_pstatus=30时）；
	v_amount=request("v_amount")                         ' 订单实际支付金额
	v_moneytype=request("v_moneytype")                   ' 订单实际支付币种
	remark2=request("remark2")                           ' 备注字段2
	v_md5str=request("v_md5str")                         ' 网银在线拼凑的Md5校验串
	if request("v_md5str")="" then
		response.Write("v_md5str：空值")
		response.end
	end if
	text = v_oid&v_pstatus&v_amount&v_moneytype&MD5Key 'md5校验
	md5text = Ucase(trim(md5(text,32)))    '商户拼凑的Md5校验串
	if md5text<>v_md5str then		' 网银在线拼凑的Md5校验串 与 商户拼凑的Md5校验串 进行对比
	  	response.write("error") '告诉服务器验证失败，要求重发
	    response.end '中断程序
	else
	  if v_pstatus=20 then '支付成功
		Call UpdateOrder(v_amount,remark2,v_oid,v_pmode)
	  else
	   	response.write("error") '告诉服务器验证失败，要求重发
	    response.end '中断程序
	  end if
	end if
	Dim message
	message="此次交易编号： " & v_oid & "<p>在线支付结果："
	if v_pstatus=20 then
		message = message & "在线支付成功"
    elseif v_pstatus=30 then
		message = message & "在线支付失败!"
   end if
    message = message & "</p><p>您所使用的卡为：" & v_pmode & "</p><p>金额：" & v_amount & "</p><p>币种：人民币</p>"
    Call ShowResult(message)
end Sub

'中国在线支付网
Sub ipayBack()
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim md5string
	v_mid = AccountID
	v_date = Trim(Request("v_date"))      '订单日期
	v_oid = Trim(KS.S("v_oid"))       '支付定单号
	v_amount = Trim(Request("v_amount"))   '订单金额
	v_pstatus = Trim(Request("v_status"))   '订单状态
	v_md5 = Trim(Request("v_md5"))         'MD5签名
	md5string = MD5(v_date & v_mid & v_oid & v_amount & v_pstatus & MD5Key, 32)
	v_pmode = ""
	v_pstring = ""
	If UCase(v_md5) = UCase(md5string) And v_pstatus = "00" Then
	    Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)
		Call ShowResult("恭喜你！在线支付成功！")
	Else
		Call ShowResult("在线支付失败！")
	End If
End Sub

'上海环迅
Sub IpsBack()
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim Billno, amount, succ, InputDate, Signature, myDate, msg, sContent, pubfilename
	Dim md5string
	v_mid = AccountID
	Billno = Trim(KS.S("billno"))
	amount = Trim(KS.S("amount"))
	succ = Trim(KS.S("succ"))
	myDate = Trim(KS.S("date"))
	InputDate = Mid(myDate, 1, 4) & "-" & Mid(myDate, 5, 2) & "-" & Mid(myDate, 7, 2)
	msg = Trim(Request.QueryString("msg"))
	Signature = Trim(Request.QueryString("signature")) '密文
	
	If succ = "Y" Then
		sContent = Billno & amount & myDate & succ    '组成明文字符进行签名
		pubfilename = "c:\secre\public.key"           'pubfilename为您保存公钥文件的全路经名
		'签名认证
		Dim secre
		Set secre = Server.CreateObject("SignandVerify.RSACom")
		If secre.VerifyMessage(pubfilename, sContent, Signature) = 0 Then
			v_oid = myDate & Right(Billno, 6)
			v_amount = amount
			v_pstring = msg
			v_pmode = ""
			Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)
			Call ShowResult("恭喜你！在线支付成功！")
		Else
			Call ShowResult("在线支付失败！")
		End If
		Set secre = Nothing
	Else
		Call ShowResult("在线支付失败！")
	End If
End Sub

'西部支付
Sub YeepayBack()
	Dim r0_Cmd:r0_Cmd		=	KS.S("r0_Cmd")
	Dim r1_Code:r1_Code		=	KS.S("r1_Code")
	Dim r2_TrxId:r2_TrxId	=	KS.S("r2_TrxId")
	Dim r3_Amt:r3_Amt		=	KS.S("r3_Amt")
	Dim r4_Cur:r4_Cur		=	KS.S("r4_Cur")
	Dim r5_Pid:r5_Pid		=	KS.S("r5_Pid")
	Dim r6_Order:r6_Order	=	KS.S("r6_Order")
	Dim r7_Uid:r7_Uid		=	KS.S("r7_Uid")
	Dim r8_MP:r8_MP			=	KS.S("r8_MP")
	Dim r9_BType:r9_BType	=	KS.S("r9_BType") 	
	Dim hmac:hmac			=	KS.S("hmac")
	
	Dim bRet:bRet = CheckHmac(r0_Cmd,r1_Code,r2_TrxId,r3_Amt,r4_Cur,r5_Pid,r6_Order,r7_Uid,r8_MP,r9_BType,hmac)

	
	If bRet = True Then
		Call UpdateOrder(r3_Amt,"在线充值，订单号为:" & r6_Order,r6_Order,"")
		Call ShowResult("恭喜你！在线支付成功！")
	Else
		Call ShowResult("在线支付失败！")
	End If
End Sub
Function getCallbackHmacString(r0_Cmd,r1_Code,r2_TrxId,r3_Amt,r4_Cur,r5_Pid,r6_Order,r7_Uid,r8_MP,r9_BType)

	'取得签名数据前的字符串，一定按照文档中标明的签名顺序进行
	dim sbOld:sbOld = AccountID & r0_Cmd & r1_Code & r2_TrxId & r3_Amt & r4_Cur & r5_Pid & r6_Order &  r7_Uid & r8_MP & r9_BType

	getCallbackHmacString = HmacMd5(sbOld,MD5Key)
	
End Function

Function CheckHmac(r0_Cmd,r1_Code,r2_TrxId,r3_Amt,r4_Cur,r5_Pid,r6_Order,r7_Uid,r8_MP,r9_BType,hmac)
	if(hmac=getCallbackHmacString(r0_Cmd,r1_Code,r2_TrxId,r3_Amt,r4_Cur,r5_Pid,r6_Order,r7_Uid,r8_MP,r9_BType)) Then
		CheckHmac = True
	ELSE
		CheckHmac = False
	END IF
End Function

'易付通
Sub xpayBack()
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim md5string,v_sid
	v_mid = AccountID
	v_oid = Trim(KS.S("bid"))       '支付定单号
	v_sid = Trim(KS.S("sid"))         '易付通交易成功 流水号
	v_md5 = Trim(Request("md"))       '数字签名
	v_amount = Trim(Request("prc"))       '支付金额
	v_pstatus = Trim(Request("success"))       '支付状态
	v_pmode = Trim(Request("bankcode"))       '支付银行
	v_pstring = Trim(Request("v_pstring"))       '支付结果说明
	
	md5string = MD5(MD5Key & ":" & v_oid & "," & v_sid & "," & v_amount & ",sell,," & v_mid & ",bank," & v_pstatus, 32)
	
	If UCase(v_md5) = UCase(md5string) And LCase(v_pstatus) = "true" Then
		Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)
		Call ShowResult("恭喜你！在线支付成功！")
	Else
		Call ShowResult("在线支付失败！")
	End If
End Sub

'云网支付
Sub cncardBack
	Dim PaySuccess:PaySuccess = False
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim md5string
	Dim c_mid, c_order, c_orderamount, c_ymd, c_transnum, c_succmark, c_moneytype, c_cause, c_memo1, c_memo2, c_signstr
	c_mid = KS.S("c_mid")                    '商户编号，在申请商户成功后即可获得，可以在申请商户成功的邮件中获取该编号
	c_order = KS.S("c_order")                '商户提供的订单号
	c_orderamount = KS.S("c_orderamount")    '商户提供的订单总金额，以元为单位，小数点后保留两位，如：13.05
	c_ymd = Request("c_ymd")                    '商户传输过来的订单产生日期，格式为"yyyymmdd"，如20050102
	c_transnum = Request("c_transnum")          '云网支付网关提供的该笔订单的交易流水号，供日后查询、核对使用；
	c_succmark = Request("c_succmark")          '交易成功标志，Y-成功 N-失败
	c_moneytype = Request("c_moneytype")        '支付币种，0为人民币
	c_cause = Request("c_cause")                '如果订单支付失败，则该值代表失败原因
	c_memo1 = Request("c_memo1")                '商户提供的需要在支付结果通知中转发的商户参数一
	c_memo2 = Request("c_memo2")                '商户提供的需要在支付结果通知中转发的商户参数二
	c_signstr = Request("c_signstr")            '云网支付网关对已上信息进行MD5加密后的字符串
	
	IF c_mid="" or c_order="" or c_orderamount="" or c_ymd="" or c_moneytype="" or c_transnum="" or c_succmark="" or c_signstr="" THEN KS.Die "出错啦！"
	
    SUserName=Split(c_memo1,"|")(1)
	SUserCardID=Split(c_memo1,"|")(3)
	sAction=Split(c_memo1,"|")(2)
	md5string = MD5(c_mid & c_order & c_orderamount & c_ymd & c_transnum & c_succmark & c_moneytype & c_memo1 & c_memo2 & MD5Key, 32)
	If UCase(md5string) <> UCase(c_signstr) Then
		Response.Write "签名验证失败"
		Response.End
	End If
	
	If Trim(AccountID) <> c_mid Then
		Response.Write "提交的商户编号有误"
		Response.End
	End If
	
	If c_succmark <> "Y" And c_succmark <> "N" Then
		Response.Write "参数提交有误"
		Response.End
	End If
	
	PaySuccess = True
	v_oid = c_order
	v_amount = c_orderamount
	v_pstring = ""
	v_pmode = ""
	If PaySuccess = True Then
		Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)
		Call ShowResult("恭喜你！在线支付成功！")
	Else
		Call ShowResult("在线支付失败！")
	End If
End Sub

'快钱支付
Sub billback()
Dim md5string
Dim merchantAcctId, key, version, language, signType, payType, bankId, orderId, orderTime, orderAmount, dealId, bankDealId, dealTime, payAmount
Dim fee, ext1, ext2, payResult, errCode, signMsg, merchantSignMsgVal

merchantAcctId = Trim(request("merchantAcctId")) '获取人民币网关账户号
key = MD5Key '设置人民币网关密钥
version = Trim(request("version")) '获取网关版本
language = Trim(request("language")) '获取语言种类,1代表中文；2代表英文
signType = Trim(request("signType")) '签名类型,1代表MD5签名
payType = Trim(request("payType")) '获取支付方式,00：组合支付,10：银行卡支付,11：电话银行支付,12：快钱账户支付,13：线下支付,14：B2B支付
bankId = Trim(KS.S("bankId")) '获取银行代码
orderId = Trim(KS.S("orderId")) '获取商户订单号
orderTime = Trim(request("orderTime")) '获取订单提交时间
orderAmount = Trim(request("orderAmount")) '获取原始订单金额
dealId = Trim(request("dealId")) '获取快钱交易号
bankDealId = Trim(request("bankDealId")) '获取银行交易号
dealTime = Trim(request("dealTime")) '获取在快钱交易时间
payAmount = Trim(request("payAmount")) '获取实际支付金额,单位为分
fee = Trim(request("fee")) '获取交易手续费
ext1 = Trim(request("ext1")) '获取扩展字段1
ext2 = Trim(request("ext2")) '获取扩展字段2

'获取处理结果
''10代表 成功11代表 失败
''00代表 下订单成功（仅对电话银行支付订单返回）;01代表 下订单失败（仅对电话银行支付订单返回）
payResult = Trim(request("payResult"))
errCode = Trim(request("errCode")) '获取错误代码,详细见文档错误代码列表
signMsg = Trim(request("signMsg")) '获取加密签名串

'生成加密串。必须保持如下顺序。
merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId", merchantAcctId)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "language", language)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType", signType)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime", orderTime)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount", orderAmount)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId", bankDealId)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime", dealTime)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount", payAmount)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult", payResult)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode)
merchantSignMsgVal = appendParam(merchantSignMsgVal, "key", key)

md5string = MD5(merchantSignMsgVal, 32)

Dim rtnOk, rtnUrl
rtnOk = 0
rtnUrl = ""

''首先进行签名字符串验证
If UCase(signMsg) = UCase(md5string) Then
    ''接着进行支付结果判断
    Select Case payResult
          Case "10"   '支付成功，更新订单
            rtnOk = 1
			Call UpdateOrder(orderAmount / 100,"在线充值，订单号为:" & orderId,orderId,"")
			Call ShowResult("恭喜你！在线支付成功！")
         Case Else
            rtnOk = 1
    End Select
Else
    rtnOk = 1
End If
%>
<result><%=rtnOk %></result><redirecturl><%=rtnUrl %></redirecturl>
<%
End Sub

Function appendParam(returnStr, paramId, paramValue)
    If returnStr <> "" Then
        If paramValue <> "" Then
            returnStr=returnStr&"&"&paramId&"="&paramValue
        End If
    Else
        If paramValue <> "" Then
            returnStr=paramId&"="&paramValue
        End If
    End If
    appendParam = returnStr
End Function
'支付宝
Sub alipayBack()
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim md5string,alipayNotifyURL
    v_mid = AccountID
	Dim Partner
	Dim ArrMD5Key
	If InStr(MD5Key, "|") > 0 Then
		ArrMD5Key = Split(MD5Key, "|")
		If UBound(ArrMD5Key) = 1 Then
			MD5Key = ArrMD5Key(0)
			Partner = ArrMD5Key(1)
		End If
	End If


	Dim trade_status, sign, MySign, Retrieval,ResponseTxt
	Dim mystr, Count, i, minmax, minmaxSlot, j, mark, temp, value, md5str, notify_id
	
	v_oid = DelStr(KS.S("out_trade_no"))            '商户定单号
	trade_status = DelStr(Request("trade_status"))
	sign = DelStr(Request("sign"))
	v_amount = DelStr(Request("total_fee"))
	notify_id = Request("notify_id")
	if RateByUser=1 then v_amount=v_amount-v_amount*PayOnlineRate/100

	alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?"
	alipayNotifyURL = alipayNotifyURL & "partner=" & Partner & "&notify_id=" & notify_id
	Set Retrieval = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
    Retrieval.setOption 2, 13056 
    Retrieval.open "GET", alipayNotifyURL, False, "", "" 
    Retrieval.send()
    ResponseTxt = Retrieval.ResponseText
	Set Retrieval = Nothing
	
	'获取Get过来的参数
    mystr = GetRequest("get")
    '验证是否有数组传来
	If IsArray(mystr) Then
		'生成签名结果
		mysign = GetMysign(mystr)
	end if	

	'********************************************************
	If ResponseTxt="true" and mysign=sign Then 	
		Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)  '因为有加了notifyurl.asp，所以可以关闭,但如果是本机测试，需要开启，即将前面的单引号删除
		Call ShowResult("恭喜你！在线支付成功！")
	Else
	    Call ShowResult("在线支付失败！")          '这里可以指定你需要显示的内容
	End If 
	
End Sub

'支付宝非即时到账
Sub alipayBack9()
    Dim PaySuccess,ResponseTxt,returnTxt
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim md5string,alipayNotifyURL
    v_mid = AccountID
	Dim Partner
	Dim ArrMD5Key
	If InStr(MD5Key, "|") > 0 Then
		ArrMD5Key = Split(MD5Key, "|")
		If UBound(ArrMD5Key) = 1 Then
			MD5Key = ArrMD5Key(0)
			Partner = ArrMD5Key(1)
		End If
	End If
    Dim trade_status, sign, MySign, Retrieval,trade_no
    Dim mystr, Count, i, minmax, minmaxSlot, j, mark, temp, value, md5str, notify_id
    sign = DelStr(Request("sign"))
    notify_id = Request("notify_id")
    alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?"
    alipayNotifyURL = alipayNotifyURL & "service=notify_verify&partner=" & Partner & "&notify_id=" & notify_id
	Set Retrieval = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
    Retrieval.Open "GET", alipayNotifyURL, False, "", ""
    Retrieval.Send
    ResponseTxt = Retrieval.ResponseText
    Set Retrieval = Nothing
                
    '获取Get过来的参数
    mystr = GetRequest("get")
    '验证是否有数组传来
	If IsArray(mystr) Then
		mysign = GetMysign(mystr) '生成签名结果
	end if	
    If ResponseTxt = "true" And sign = MySign Then
	  call alipayprocess()
	Else
	  Call ShowResult("在线支付失败！")
	End If

End Sub

sub alipayprocess()
    Dim v_pmode
    Dim trade_status:trade_status = DelStr(KS.S("trade_status"))
	Dim v_oid:v_oid = DelStr(KS.S("out_trade_no"))            '商户定单号
	Dim trade_no:trade_no= KS.S("trade_no")		'获取支付宝交易号
    Dim v_amount:v_amount = Request("price")
	if not isnumeric(v_amount) or v_amount="" then  v_amount=request("total_fee")
	if not isnumeric(v_amount) or v_amount="" then  v_amount=0
  
    if trade_status<>"" then
    Conn.Execute("Update KS_Order Set alipaytradestatus='" &trade_status & "' Where OrderID='" & v_oid & "'") '更新支付记录状态和发货状态
   end if
   
   
    '等待买家付款
    Select Case trade_status
    Case "WAIT_BUYER_PAY"

    '买家付款成功,等待卖家发货
    Case "WAIT_SELLER_SEND_GOODS"
			Conn.Execute("Update KS_Order Set Status=1,MoneyReceipt=" &v_amount & " Where OrderID='" & KS.R(v_oid) & "'") '只更新订单状态，不更新发货状态和订单状态
			Dim RS:Set RS=Server.CreateObject("ADODB.RECORDSET")
			RS.Open "Select top 1 * From KS_Order Where OrderID='" & KS.R(v_oid) & "'",Conn,1,3
			If Not RS.Eof Then
			  If RS("MoneyReceipt")>=RS("MoneyTotal") Then
		  	    RS("PayStatus")=1  '已付清
			  ElseIf RS("MoneyReceipt")<>0 Then
				 RS("PayStatus")=2  '已收定金
			  Else
				 RS("PayStatus")=0  '未付款
			  End If
			  rs("PaymentPlatId")=PaymentPlat
			  RS.Update
			End If
			RS.Close:Set RS=Nothing
			Call ShowResult("恭喜你！在线支付成功！")
			KS.Die ""
    '等待买家确认收货
    Case "WAIT_BUYER_CONFIRM_GOODS"
            Conn.Execute("Update KS_Order Set Status=1,DeliverStatus=1 Where OrderID='" & v_oid & "'") '更新支付记录状态和发货状态，不更新订单状态

    '交易成功结束
    Case "TRADE_FINISHED"
        Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)
		Call ShowResult("恭喜你！在线支付成功！")
    '其他交易状态通知情况
    Case Else
        
    End Select
	
end sub



Function DelStr(Str)
		If IsNull(Str) Or IsEmpty(Str) Then
			Str	= ""
		End If
		DelStr	= Replace(Str,";","")
		DelStr	= Replace(DelStr,"'","")
		DelStr	= Replace(DelStr,"&","")
		DelStr	= Replace(DelStr," ","")
		DelStr	= Replace(DelStr,"　","")
		DelStr	= Replace(DelStr,"%20","")
		DelStr	= Replace(DelStr,"--","")
		DelStr	= Replace(DelStr,"==","")
		DelStr	= Replace(DelStr,"<","")
		DelStr	= Replace(DelStr,">","")
		DelStr	= Replace(DelStr,"%","")
End Function


'财付通
Sub tenpayback()
	Dim v_mid, v_oid, v_pmode, v_pstatus, v_pstring, v_amount, v_md5, v_date, v_moneytype
	Dim md5string
	v_mid = AccountID
	
	Dim cmdno, pay_result, pay_info, bill_date, bargainor_id, transaction_id, sp_billno, total_fee, fee_type, md5_sign, attach
	cmdno = KS.S("cmdno")
	pay_result = Request("pay_result")
	pay_info = Request("pay_info")
	bill_date = Request("date")
	bargainor_id = Request("bargainor_id")
	transaction_id = Request("transaction_id")
	sp_billno = KS.S("sp_billno")
	total_fee = Request("total_fee")
	fee_type = Request("fee_type")
	attach = Request("attach")
	md5_sign = Request("sign")
	
	md5string = MD5("cmdno=" & cmdno & "&pay_result=" & pay_result & "&date=" & bill_date & "&transaction_id=" & transaction_id & "&sp_billno=" & sp_billno & "&total_fee=" & total_fee & "&fee_type=" & fee_type & "&attach=" & attach & "&key=" & MD5Key, 32)
	
	If bargainor_id = v_mid And UCase(md5string) = md5_sign And pay_result = 0 Then
		v_oid = sp_billno
		v_amount = total_fee / 100
		v_pstring = ""
		v_pmode = ""
		Call UpdateOrder(v_amount,"在线充值，订单号为:" & v_oid,v_oid,v_pmode)
		Call ShowResult("恭喜你！在线支付成功！")
	Else
		Call ShowResult("在线支付失败！")
	End If
End Sub

'财付通中介
Sub tenpayZJ()
%>
<html>
<head>
	<meta name="TENCENT_ONLINE_PAYMENT" content="China TENCENT">
</head>
<%
'获取参数
Dim attach,buyer_id,cft_tid,chnid,mch_vno,cmdno,retcode,seller,status,total_fee,trade_price,transport_fee,version,sign,localSignText	
attach					= KS.S("attach")
buyer_id				= KS.S("buyer_id")
cft_tid					= KS.S("cft_tid")
chnid					= KS.S("chnid")
cmdno					= KS.S("cmdno")
mch_vno					= KS.S("mch_vno")

retcode					= KS.S("retcode")
seller					= KS.S("seller")
status					= KS.S("status")

total_fee				= KS.S("total_fee")
trade_price				= KS.S("trade_price")
transport_fee			= KS.S("transport_fee")
version                 = KS.S("version")

sign					= Request("sign")

dim buffer
buffer = appendParam(buffer, "attach", 		attach)
buffer = appendParam(buffer, "buyer_id", 		buyer_id)
buffer = appendParam(buffer, "cft_tid", 		cft_tid)
buffer = appendParam(buffer, "chnid", 			chnid)
buffer = appendParam(buffer, "cmdno", 			cmdno)
buffer = appendParam(buffer, "mch_vno", 		mch_vno)
buffer = appendParam(buffer, "retcode", 		retcode)
buffer = appendParam(buffer, "seller", 		seller)
buffer = appendParam(buffer, "status", 		status)
buffer = appendParam(buffer, "total_fee", 		total_fee)
buffer = appendParam(buffer, "trade_price", 	trade_price)
buffer = appendParam(buffer, "transport_fee", 	transport_fee)
buffer = appendParam(buffer, "version", 	version)

buffer = appendParam(buffer, "key",			MD5Key)

'生成签名
localSignText = UCase(md5(buffer,32) )

dim msg
'签名判断
if localSignText = sign then
	'认证签名成功
	
	if retcode = "0" then
		msg = "OK"
		msg = msg & status 
		Select case status
			case "1":
				'交易创建
			case "2":
				'收获地址填写完毕
			case "3":
				Conn.Execute("Update KS_Order Set MoneyReceipt=MoneyTotal,Status=1 Where OrderID='" & KS.R(mch_vno) & "'") '更新订单状态及已付款
                response.write "<script>alert('恭喜，支付成功！请等待商家发货！');location.href='../user/index.asp?user_order.asp';</script>"
			case "4":
				Conn.Execute("Update KS_Order Set DeliverStatus=1 Where OrderID='" & KS.R(mch_vno) & "'")
				'卖家发货成功
			case "5":
				Conn.Execute("Update KS_Order Set DeliverStatus=2 Where OrderID='" & KS.R(mch_vno) & "'")
				'买家收货确认，交易成功
			case "6":
				'交易关闭，未完成超时关闭
			case "7":
				'修改交易价格成功
			case "8":
				'买家发起退款
			case "9":
				'退款成功
			case "10":
				'退款关闭
			case else
				'error
		end Select

	else
		'支付失败，请不要按成功处理
		msg = "支付失败"
	end if

else
	'认证签名失败
	msg = "认证签名失败"
end if

%>
<body>
	<div align="center"><%=msg%></div>
</body>
</html>
<%
End Sub



Sub ShowResult(byval message)
Session(KS.SiteSN&"UserInfo")=empty
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户管理中心</title>
<link href="images/css.css" type="text/css" rel="stylesheet" />
</head>
<body leftmargin="0" bottommargin="0" rightmargin="0" topmargin="0"><br><br><br>
	<table class=border cellSpacing=1 cellPadding=2 width="60%" align=center border=0>
  <tr class="title"> 
    <td height=22 align=center><b><font color="#FF0000">提示：</font> 您网上在线支付情况反馈如下：</b></td>
 </tr>
 <tr class="tdbg"><td>
      <p>
        <%=message%>
	  </p>
     </td>
  </tr>
  <tr class="title">
   <td  height="22" align="center"><a href="<%=KS.getdomain%>user/index.asp">进入会员中心</a> | <a href="<%=KS.getdomain%>">返回首页</a>
   </td>
  </tr>
</table>
<%
End Sub
%>